package serve

import (
	"aquaman/app/infra/log"
	"context"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"net"
	"os"
	"os/signal"
	"syscall"
	//"time"
)

type App struct {
	config     *viper.Viper
	logger     log.Logger
	//httpServer *http.Server
	grpcServer *grpc.Server
	listener   net.Listener
	//dbconfig   *dbconfig.DBConfig
}

func NewApp(
	viper *viper.Viper,
	//http *http.Server,
	grpc *grpc.Server,
	lis net.Listener,
	logger log.Logger,
	//dbconfig *dbconfig.DBConfig,
) *App {
	return &App{
		config:     viper,
		logger:     logger,
		//httpServer: http,
		grpcServer: grpc,
		listener:   lis,
		//dbconfig:   dbconfig,
	}
}

func (app *App) Run(ctx context.Context) {
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	if app.grpcServer != nil {
		go func() {
			if err := app.grpcServer.Serve(app.listener); err != nil {
				panic(errors.Wrap(err, "gRPC server error"))
			}
			app.logger.Info("gRPC Server stopped")
		}()
	}
	<-quit
	if app.grpcServer != nil {
		app.grpcServer.GracefulStop()
		app.logger.Info("gRPC Server exit.")
	}
	app.logger.Info("goodbye Aquaman!")
}